using Digitalmes.Application.Mes.Productions.Products;
using Digitalmes.Domain.Entities.Mes.Productions;
using Digitalmes.Domain.Entities.Mes.Reworks;

namespace Digitalmes.Application.Mes.Reworks.Doc.Queries;

/// <summary>
/// 分页查询可返工产品列表命令。
/// </summary>
public sealed record GetReworkableListWithPagedQuery(
    string? Sn,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<ProdCurrentStateDto>>>;

internal sealed class GetReworkableListWithPagedQueryHandler(IRepository<ProdCurrentState> repo)
    : IRequestHandler<GetReworkableListWithPagedQuery, IResult<PagedList<ProdCurrentStateDto>>>
{
    public async Task<IResult<PagedList<ProdCurrentStateDto>>> Handle(GetReworkableListWithPagedQuery request, CancellationToken cancellationToken)
    {
        // 查找不合格或强制不合格的产品，且产品不处于返工中或返工中状态。
        var items = await repo.AsQueryable()
            .Where(m => m.Status == PassEnum.NG || m.Status == PassEnum.ForceNG)
            .WhereIF(!string.IsNullOrEmpty(request.Sn), m => m.Sn == request.Sn)
            .Where(m => SqlSugar.SqlFunc.Subqueryable<ReworkDoc>()
                .Where(s => s.Sn == m.Sn && (s.Status == ReworkStatusEnum.Created || s.Status == ReworkStatusEnum.Reworking))
                .NotAny())
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);
        return Result.From(items.Adapt<PagedList<ProdCurrentStateDto>>());
    }
}
